<template>
  <view>
    <!-- 日期选择弹窗 -->
    <u-popup mode="bottom" :show="show" @close="onClose" border-radius="16">
      <view class="date-picker-container">
        <!-- 顶部显示选中的日期 -->
        <view class="selected-date-display">
          <view class="date-display-row">
            <text class="date-label">公历：</text>
            <text class="selected-date-text">{{ solarDisplayText }}</text>
          </view>
        </view>

        <view class="date-picker-header">
          <text class="cancel-btn" @tap="onCancel">取消</text>
          <text class="confirm-btn" @click="confirmPicker">确认</text>
        </view>

        <view class="date-picker-body">
          <picker-view :value="datePickerValue" @change="onDatePickerChange" class="date-picker">
            <picker-view-column v-for="(column, columnIndex) in columns" :key="columnIndex">
              <view class="picker-item" v-for="(item, index) in column.values" :key="`${column.type}-${index}`">
                {{ item }}{{ column.suffix || '' }}
              </view>
            </picker-view-column>
          </picker-view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>

export default {
  name: 'DatePicker',
  props: {
    show: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      years: [],
      months: [],
      days: [],
      hours: [],
      columns: [],
      datePickerValue: [0, 0, 0, 0],
      solarDisplayText: '',
      daysInMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    };
  },
  created() {
    this.initDateData();
  },
  watch: {
    // 使用深度监听
    datePickerValue: {
      handler(newVal, oldVal) {
        // 只有年份或月份变化时才更新天数
        if (!oldVal || newVal[0] !== oldVal[0] || newVal[1] !== oldVal[1]) {
          this.updateDaysInMonth();
        }

        // 任何变化都更新显示文本
        this.updateDisplayDateText();
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    // 初始化时更新天数和显示文本
    this.updateDaysInMonth();
    this.updateDisplayDateText();
  },
  methods: {
    // 初始化日期数据
    initDateData() {
      const currentDate = new Date();
      const currentYear = currentDate.getFullYear();
      const currentMonth = currentDate.getMonth(); // 0-11
      const currentDay = currentDate.getDate() - 1; // 转为索引，从0开始
      const currentHour = currentDate.getHours(); // 获取当前小时

      // 生成年份数组：当前年份前后50年
      this.years = Array.from({ length: 100 }, (_, i) => currentYear - 75 + i);
      // 公历月份：1-12月
      this.months = Array.from({ length: 12 }, (_, i) => i + 1);
      // 默认先生成31天
      this.days = Array.from({ length: 31 }, (_, i) => i + 1);

      // 生成0-23小时
      this.hours = Array.from({ length: 24 }, (_, i) => i);

      // 初始化列配置
      this.columns = [
        { type: 'year', values: this.years, suffix: '' },
        { type: 'month', values: this.months, suffix: '月' },
        { type: 'day', values: this.days, suffix: '日' },
        { type: 'hour', values: this.hours, suffix: '时' }
      ];

      // 设置默认选中值
      this.datePickerValue = [75, currentMonth, currentDay, currentHour]; // 默认值：当前年月日时
    },

    // 更新当月天数
    updateDaysInMonth() {
      const yearIndex = this.datePickerValue[0];
      const monthIndex = this.datePickerValue[1];

      if (yearIndex < 0 || yearIndex >= this.years.length ||
        monthIndex < 0 || monthIndex >= this.months.length) {
        return;
      }

      const year = this.years[yearIndex];
      const month = this.months[monthIndex];

      // 计算该月天数，处理闰年二月
      let daysInMonth = this.daysInMonth[monthIndex];
      if (month === 2) {
        const isLeapYear = (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
        daysInMonth = isLeapYear ? 29 : 28;
      }

      // 更新天数数组
      this.days = Array.from({ length: daysInMonth }, (_, i) => i + 1);
      this.columns[2].values = this.days;

      // 确保日期不超过该月最大天数
      if (this.datePickerValue[2] >= daysInMonth) {
        this.datePickerValue[2] = daysInMonth - 1;
      }
    },

    // 日期选择器变化事件
    onDatePickerChange(e) {
      this.datePickerValue = e.detail.value;
      this.updateDisplayDateText();
    },

    // 更新顶部显示的日期文本
    updateDisplayDateText() {
      const [yearIndex, monthIndex, dayIndex, hourIndex] = this.datePickerValue;

      // 检查索引有效性
      if (yearIndex < 0 || monthIndex < 0 || dayIndex < 0 ||
        yearIndex >= this.years.length ||
        monthIndex >= this.months.length ||
        dayIndex >= this.days.length) {
        this.solarDisplayText = '';
        return;
      }

      const year = this.years[yearIndex];
      const month = this.months[monthIndex];
      const day = this.days[dayIndex];
      const hour = this.hours[hourIndex];

      // 公历显示
      this.solarDisplayText = `${year}年${month}月${day}日 ${hour}时`;
    },

    // 确认日期选择
    confirmPicker() {
      try {
        const [yearIndex, monthIndex, dayIndex, hourIndex] = this.datePickerValue;

        // 确保索引有效
        if (yearIndex < 0 || yearIndex >= this.years.length ||
          monthIndex < 0 || monthIndex >= this.months.length ||
          dayIndex < 0 || dayIndex >= this.days.length ||
          hourIndex < 0 || hourIndex >= this.hours.length) {
          return;
        }

        // 获取公历日期
        const solarYear = this.years[yearIndex];
        const solarMonth = this.months[monthIndex];
        const solarDay = this.days[dayIndex];

        // 获取小时值
        const hourValue = this.hours[hourIndex];

        // 向父组件传递选中的日期数据
        this.$emit('confirm', {
          year: solarYear,
          month: solarMonth,
          day: solarDay,
          hour: hourValue,
          minute: 0,
          birthText: this.solarDisplayText
        });

        this.$emit('close');
      } catch (error) {
        console.error('日期选择错误:', error);
        this.$emit('error', '日期选择错误，请重新选择');
      }
    },

    // 取消选择
    onCancel() {
      this.$emit('cancel');
    },

    // 关闭弹窗
    onClose() {
      this.$emit('close');
    }
  }
};
</script>

<style lang="scss" scoped>
.date-picker-container {
  background-color: #fff;
  padding: 20px;
  border-top-left-radius: 16px;
  border-top-right-radius: 16px;
}

.selected-date-display {
  padding: 10px 0;
  border-bottom: 1px solid #eee;
  margin-bottom: 15px;
}

.date-display-row {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.date-label {
  font-size: 14px;
  color: #666;
  width: 50px;
}

.selected-date-text {
  font-size: 16px;
  font-weight: bold;
  color: #ff6034;
  flex: 1;
}

.date-picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.tab-title {
  font-size: 16px;
  font-weight: bold;
}

.cancel-btn,
.confirm-btn {
  padding: 10px;
  font-size: 14px;
}

.cancel-btn {
  color: #999;
}

.confirm-btn {
  color: #ff6034;
  font-weight: bold;
}

.date-picker-body {
  padding: 20px 0;
}

.date-picker {
  height: 200px;
  width: 100%;
}

.picker-item {
  line-height: 40px;
  text-align: center;
}
</style>